package com.jjxliu.deform.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jjxliu.deform.dao.UeEntryDao;
import com.jjxliu.deform.dao.UeFormDao;
import com.jjxliu.deform.model.ueform.field.FormField;
import com.jjxliu.deform.model.ueform.field.ListCtrl;
import com.jjxliu.deform.model.ueform.field.Text;
import com.jjxliu.deform.pojo.UeEntry;
import com.jjxliu.deform.pojo.UeForm;
import com.jjxliu.deform.service.UeService;

@Service
public class UeServiceImpl implements UeService {
	
	@Autowired
	private UeFormDao formDao ;
	
	@Autowired
	private UeEntryDao entryDao;

	public String addForm(UeForm form) {
		// TODO Auto-generated method stub
		String name = form.getForm_name();
		if(name == null){
			return "表单名称不能为空" ;
		}
		UeForm hasName = formDao.findByName(name);
		if(hasName != null) {
			return "该表单名称已存在" ;
		}
		form.setCrtime(new Date());
		form.setModify_time(new Date());
		formDao.insert(form);
		
		return null;
	}

	public String removeForm(int form_id) {
		// TODO Auto-generated method stub
		
		formDao.delete(form_id);
		
		return null;
	}

	public String updateForm(UeForm form) {
		// TODO Auto-generated method stub
		String name = form.getForm_name();
		if(name == null){
			return "表单名称不能为空" ;
		}
		UeForm hasName = formDao.findByName(name);
		if(hasName != null && !hasName.getForm_id().equals(form.getForm_id())) {
			return "该表单名称已存在" ;
		}
		form.setModify_time(new Date());
		formDao.update(form);
		
		
		return null ;
	}
	

	public List<UeForm> findAllForms() {
		// TODO Auto-generated method stub
		 List<UeForm> list = formDao.findAll();
	 
		 
		 return list ;
	}

	public UeForm findByFormId(int form_id ) {
		// TODO Auto-generated method stub
		UeForm form = formDao.findById(form_id);
		 
		return form ;
	}
	
	/*private UeForm updateTemplateListCtrl(UeForm form , String value) {
		
		String formeditor = form.getTemplate();
		String data =  form.getData();

		if(formeditor != null && formeditor.trim().length() > 1) {
			formeditor = formeditor.replace("{|-", "").replace("-|}", "");
			//System.out.println("formeditor : " + formeditor);

			if(formeditor.contains("listctrl")) {

				JSONArray jarray = JSON.parseArray(data);
				Iterator<Object> iters = jarray.iterator();
				while(iters.hasNext()) {

					Object iter = iters.next();
					if(iter.toString().contains("listctrl")) {
						formeditor = CommonUtils.parseListCtrl(iter.toString(), formeditor , value);
						form.setTemplate(formeditor);
						break ;
					}

				} 
			}


		}
		return form ;
	}*/

	public String addEntry(UeEntry entry) {
		 
		
		String error = validEntry(entry);
		
		if(error != null) return error ;
		
		entry.setCrtime(new Date());
		entry.setModify_time(new Date());
		entryDao.insert(entry);
		
		return null;
	}

	public void removeEntry(int id) {
		// TODO Auto-generated method stub
		entryDao.delete(id);
	}
	
	private String validEntry(UeEntry entry) {
		
		UeForm f = findByFormId(entry.getForm_id());
		
		List<FormField> ffs = f.getForm_fields();
		
		JSONObject jsonValue = JSON.parseObject(entry.getValue());
		
		for(FormField ff : ffs) {
			
			if(ff.getNotnull() == null || !ff.getNotnull().trim().contains("1")) continue ;
			 
			//验证非空
			String ff_value = jsonValue.getString(ff.getName());
			if(ff_value == null || ff_value.trim().equals("") || (ff.getLeipiplugins().equals("checkboxs") && ff_value.trim().equals("[]") )) {

				return ff.getTitle() +  " 不能为空 ";

			}
			//判断listctrl中表单字段是否可以为空 
			if(ff.getLeipiplugins().equals("listctrl")) {

				ListCtrl lc = (ListCtrl)ff;

				String notnulls = lc.getNotnull();

				if(notnulls == null || notnulls.trim().length() < 1) continue ;


				//分割 是否要验证
				String[] nns = notnulls.split("`");
				//字段名
				String[] cols = lc.getOrgtitle().split("`");
				//字段key
				String[] col_keys = lc.getOrgkey().split("`");
				//字段类型
				String[] col_types = lc.getOrgcoltype().split("`");

				//值
				JSONObject list_value = jsonValue.getJSONObject(ff.getName());

				Set<String> indexes = list_value.keySet();

				for(String index : indexes) {
					
					if(!index.matches("^\\d+$")) continue ;
					
					int _index = Integer.valueOf(index) + 1;
					
					//每一行的value
					//key 其实为具体table中的行号 从0开始
					JSONObject line_value = list_value.getJSONObject(index);

					for(int k = 0 ; k < cols.length && k < col_keys.length ; k++) {
						String l_v = line_value.getString(col_keys[k]);

						if(!nns[k].equals("1")) continue ; //不需要验证
						
						//如果类型直接过
						if(l_v == null || l_v.trim().length() < 1 ) {
							
							return ff.getTitle() +  " 中第" + _index + "行中字段 - " + cols[k] + " 不能为空 ";
						} else {
							
							//数字 
							if(col_types != null && col_types.length > k && col_types[k] != null && col_types[k].equals("int") && !l_v.matches("^-?\\d+(.\\d+)?$")) {
								
								return ff.getTitle() +  " 中第" + _index + "行中字段 - " + cols[k] + " 值只能为数字 ";
								
							}
							
						}
						

					}

				} 
			} else if(ff.getLeipiplugins().trim().equals("text")) {
				//判断文本 要验证具体值类型

				/* <option value="text">普通文本</option>
	                <option value="email">邮箱地址</option>
	                <option value="int">整数</option>
	                <option value="float">小数</option>
	                <option value="idcard">身份证号码</option>*/
				String type = ((Text)ff).getOrgtype();
				if(type.equals("text")) continue ;
				else if(type.equals("int") && !ff_value.matches("^-?\\d+$")) {
					return ff.getTitle() +  " 值只能为整数 ";
				}
				else if(type.equals("float") && !ff_value.matches("^-?\\d+(\\.\\d+)?$")){
					return ff.getTitle() +  " 值只能为数字 ";
				}
				else if(type.equals("idcard") &&!ff_value.matches("^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$")) {
					return ff.getTitle() +  " 不是身份证编码 ";
				}
				else if(type.equals("email") && !ff_value.matches("^[0-9A-Za-z][\\.-_0-9A-Za-z]*@[0-9A-Za-z]+(\\.[0-9A-Za-z]+)+$")){
					return ff.getTitle() +  " 不是邮箱格式 ";
				}

			}

			
		}
		
		
		return null ;
	}

	public String updateEntry(UeEntry entry) {
		// TODO Auto-generated method stub
		 
		
		String error = validEntry(entry);
		
		if(error != null) return error ;
		
		entry.setModify_time(new Date());
		
		 entryDao.update(entry);
		 
		 return null;
	}

	public List<UeEntry> findAllEntry() {
		// TODO Auto-generated method stub
		return entryDao.findAll();
	}

	public UeEntry findById(int entry_id) {
		// TODO Auto-generated method stub
		return entryDao.findById(entry_id);
	}

	 

}
